package spring.proxy;

import java.lang.reflect.Proxy;
import java.util.Objects;

public class JdkBeanProxy {

    JdkBeanProxy() {
    }

    @SuppressWarnings("unchecked")
    public <T> T getProxyInstance(T originObject, Class<?>... args) {
        Class<?>[] interfaces = getInterfaces(originObject.getClass());
        if (Objects.isNull(interfaces)) {
            throw new ProxyException("The current proxy object does not have a valid interface.");
        }
        ClassLoader classLoader = originObject.getClass().getClassLoader();
        return (T) Proxy.newProxyInstance(classLoader, interfaces, new BeanHandler(originObject));
    }

    private Class<?>[] getInterfaces(Class<?> cls) {
        if (cls == null || Object.class.equals(cls)) {
            return null;
        }
        Class<?>[] interfaces = cls.getInterfaces();
        if (interfaces.length == 0) {
            return getInterfaces(cls.getSuperclass());
        }
        return interfaces;
    }

}
